<template>
  <PageMain>
    <template #header></template>
    <template #body>
      <div class="layout w-full h-full box-border bg-white p-[20px] main-container"  ref="RefLayout">
        <div class="search box-border pb-[20px]">
          <a-row>
            <a-col :span="12" class="common-col">
              <a-input
                class="search-item"
                v-model="filterData.name"
                placeholder="请输入资源名称搜索"
                style="width: 328px"
                allow-clear
                @clear="getTableData"
              >
                <template #suffix>
                  <a-link type="primary">
                    <icon-search @click="getTableData" class="cursor-pointer" />
                  </a-link>
                </template>
              </a-input>
              <a-button
                class="ml-2 bg-[#E5EFFE!important] cursor-pointer"
                @click="moreFilterKey = !moreFilterKey"
              >
                <template #icon>
                  <icon-filter style="color: #A3B0CC" />
                </template>
              </a-button>
            </a-col>
            <a-col :span="12" class="flex justify-end header-right-btn" >
              <a-button class="association-btn" @click="importData.relation.key = true">同步关联</a-button>
              <a-dropdown-button type="primary" trigger="hover" @click="assetAdd">
                添加资源
                <template #icon>
                  <icon-down />
                </template>
                <template #content>
                  <a-doption @click.stop="importData.import.key = true">批量导入</a-doption>
                </template>
              </a-dropdown-button>
            </a-col>
          </a-row>
          <div
            class="more-fliter-box w-full h-[120px] mt-[20px] mb-0 p-[20px] pl-[10px] pr-[10px] box-border bg-[#F7F9FC]"
            v-if="moreFilterKey"
          >
            <a-row class="w-full h-[40px] overflow-hidden" justify="start">
              <a-col :span="8">
                <a-select
                  class="search-item"
                  v-model="filterData.consanguinity_status"
                  placeholder="请选择"
                  allow-clear
                  @change="getTableData"
                >
                  <template #prefix> 关联状态 </template>
                  <a-option :value="1">已同步</a-option>
                  <a-option :value="2">未同步</a-option>
                </a-select>
              </a-col>
              <a-col :span="8">
                <a-range-picker
                  class="search-item"
                  v-model="filterData.create_time"
                  @change="getTableData"
                  style="width: 100%"
                >
                  <template #prefix> 添加时间 </template>
                </a-range-picker>
              </a-col>
              <a-col :span="8">
                <a-input-number
                  class="search-item"
                  v-model="filterData.version"
                  placeholder="请输入"
                  allow-clear
                  :precision="0"
                  @change="getTableData"
                >
                  <template #prefix> 资源版本 </template>
                </a-input-number>
                <!-- <a-select class="search-item" v-model="filterData.version" placeholder="请选择" allow-clear>
                  <template #prefix> 资源版本 </template>
                  <template v-for="index in 10" :key="index">
                    <a-option :value="index">V{{ index }}</a-option>
                  </template>
                </a-select> -->
              </a-col>
            </a-row>
            <a-row class="w-full h-[40px] overflow-hidden" justify="start">
              <a-col :span="8">
                <a-range-picker
                  class="search-item"
                  v-model="filterData.update_time"
                  @change="getTableData"
                  style="width: 100%"
                >
                  <template #prefix> 更新时间 </template>
                </a-range-picker>
              </a-col>
              <a-col :span="8">
                <a-select
                  class="search-item"
                  v-model="filterData.is_root"
                  placeholder="请选择"
                  allow-clear
                  @change="getTableData"
                >
                  <template #prefix> 是否根资源 </template>
                  <a-option :value="1">根资源</a-option>
                  <a-option :value="2">非根资源</a-option>
                </a-select>
              </a-col>
              <a-col :span="8">
                <a-link @click="resetFilter">重置</a-link>
              </a-col>
            </a-row>
          </div>
        </div>

        <div
          class="table-box w-full"
          :style="{
            height: 'auto',
            maxHeight: moreFilterKey ? 'calc(100% - 232px)' : 'calc(100% - 92px)'
          }"
        >
          <CommonTable
            :tableData="listData"
            :columnsData="columns"
            :operatorData="operatorData"
            :pageTotal="page.total"
            @handlerOperator="handlerOperator"
            @handlerPaginationChange="handlerPaginationChange"
          >
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #version="{ record }"> V {{ record.version }}.0 </template>
            <template #is_root="{ record }">
              {{ record.is_root === 1 ? '根资源' : '非根资源' }}
            </template>
            <template #sync_consanguinity="{ record }">
              <span v-if="record.sync_consanguinity" class="flex justify-start items-center">
                <div class="circle-point border-[#34C94F] mr-2"></div>
                已关联
              </span>
              <span v-else class="flex justify-start items-center">
                <div class="circle-point border-[#FFAC38] mr-2"></div>
                未关联
              </span>
            </template>
          </CommonTable>
          <Pagination 
            :total="page.total"
            :currentPage="page.page"
            :pageSize="page.page_size"
            @currentPage="changeCurrentPage" 
            @changeSize="changeSize"
             />
        </div>
      </div>
      <a-modal
        v-model:visible="removePopKey"
        title-align="start"
        :popup-container="RefLayout"
        width="448px"
      >
        <template #title>
          <span
            style="font-family: Microsoft YaHei; font-size: 16px; font-weight: bold; color: #394d73"
            >是否确认删除该资源</span
          >
        </template>
        <div
          class="chunk-delete-info-box"
          style="font-family: Microsoft YaHei; font-size: 14px; font-weight: normal; color: #465a80"
        >
          <icon-exclamation-circle-fill style="color: #FFAC38;" />
          删除后该资源无法恢复
        </div>
        <template #footer>
          <div class="w-full h-full flex justify-end items-center">
            <a-button @click="removePopKey = false">取消</a-button>
            <a-button type="primary" class="ml-2" @click="toRemove">删除</a-button>
          </div>
        </template>
      </a-modal>
      <importBox
        :visible="importData.import.key"
        title="批量上传"
        :action="importData.import.path"
        :template="importData.import.template"
        :upload-props="{
          error: handlerUploadError,
          success: getTableData,
          accept: '.xls,.xlsx',
          onBeforeUpload: handlerFileSize
        }"
        @close="
          () => {
            importData.import.key = false;
            getTableData();
          }
        "
      />
      <importBox
        :visible="importData.relation.key"
        title="同步关联"
        :action="importData.relation.path"
        :template="importData.relation.template"
        :upload-props="{
          onError: handlerUploadError,
          success: getTableData,
          accept: '.xls,.xlsx',
          onBeforeUpload: handlerFileSize
        }"
        @close="
          () => {
            importData.relation.key = false;
            getTableData();
          }
        "
      />
    </template>
  </PageMain>
</template>
<script lang="ts" setup>
import * as Api from '@/api/assetManagement/assetManagement';
import * as T from '@/api/assetManagement/assetManagement_type';
import PageMain from '@/components/PageBox.vue';
import Pagination from '@/views/resource_ledger/components/Pagination.vue';
import { Message } from '@arco-design/web-vue';
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import importBox from '../../components/importPopBox.vue';
import { columns, operatorData } from './values';

import CommonTable from '@/views/asset_management/resource_management/components/CommonTable.vue';

const serverPath = import.meta.env.VITE_API_BASE_URL;

const router = useRouter();
const route = useRoute();
const RefLayout = ref();
const importData = ref({
  relation: {
    key: false,
    path: `${serverPath}/api/asset/resource/sync_consanguinity`,
    template: '血缘导入模板.xlsx'
  },
  import: {
    key: false,
    path: `${serverPath}/api/asset/resource/import`,
    template: '资源导入模版.xlsx'
  }
});
// filter 筛选条件
const filterData = ref({
  name: '', // 资源名称
  is_root: '', // 是否根资源 2, 1
  create_time: [], // 创建时间 格式: ['2024-04-08 00:00:00', '2024-04-08 00:00:00']
  created_start_time: '', // 创建开始时间 格式: 2024-04-08 00:00:00
  created_end_time: '', // 创建结束时间 格式: 2024-04-08 00:00:00
  consanguinity_status: '', // 血缘关系状态  1: 未同步 2:已同步
  all_version: '', // 是否所有版本 1:False 2:True
  version: 0, // 版本
  update_time: [], // 更新时间 格式: ['2024-04-08 00:00:00', '2024-04-08 00:00:00']
  update_start_time: '', // 更新开始时间 格式: 2024-04-08 00:00:00
  update_end_time: '' // 更新结束时间 格式: 2024-04-08 00:00:00
});
const page = ref({
  page: 1,
  page_size: 10,
  total: 0
});
const moreFilterKey = ref(false);
// table表格数据
const listData = ref<T.TResourceList>([]);

function resetFilter() {
  filterData.value = {
    name: '', // 资源名称
    is_root: '', // 是否根资源 2, 1
    create_time: [], // 创建时间 格式: ['2024-04-08 00:00:00', '2024-04-08 00:00:00']
    created_start_time: '', // 创建开始时间 格式: 2024-04-08 00:00:00
    created_end_time: '', // 创建结束时间 格式: 2024-04-08 00:00:00
    consanguinity_status: '', // 血缘关系状态  1: 未同步 2:已同步
    all_version: '', // 是否所有版本 1:False 2:True
    version: '', // 版本
    update_time: [], // 更新时间 格式: ['2024-04-08 00:00:00', '2024-04-08 00:00:00']
    update_start_time: '', // 更新开始时间 格式: 2024-04-08 00:00:00
    update_end_time: '' // 更新结束时间 格式: 2024-04-08 00:00:00
  };
  nextTick(() => {
    getTableData();
  });
}
const changeCurrentPage = (current:number) => {
  console.log(current,'current...')
  page.value.page = current;
  getTableData();
}
const changeSize = (size:number) => {
  // console.log(size,'size...')
  page.value.page = 1;
  page.value.page_size = size;
  getTableData();
}
function handlerPaginationChange(type: string, num: number) {
  if (type === 'num') {
    page.value.page = num;
  } else {
    page.value.page = 1;
    page.value.page_size = num;
  }
  nextTick(() => {
    getTableData();
  });
}

function handlerFileSize(file: File) {
  const { size } = file;
  if (size > 50 * 1024 * 1024) {
    Message.warning('文件大小不能超过50M');
    return false;
  }
  return true;
}

// 请求表格数据
const loading = ref(false);
function getTableData() {
  /* listData.value =[
    {
      index:1,
      id: 1,
      name: '资源名称',
      version: 'V 1.0',
      is_root: '非根资源',
      sync_consanguinity: 1,
      created_time: '2024-04-08 00:00:00',
      update_time: '2024-04-08 00:00:00'
    },
    {
      index:2,
      id: 2,
      name: '资源名称AA',
      version: 'V 2.0',
      is_root: '根资源',
      created_time: '2024-04-08 00:00:00',
      sync_consanguinity: 0,
      update_time: '2024-04-08 00:00:00'
    }
  ]*/
  if (loading.value) return;
  loading.value = true;
  Api.getList(page.value, filterData.value)
    .then((rs) => {
      loading.value = false;
      const { code, data, total } = rs;
      if (code === 200 && data) {
        listData.value = data;
        page.value.total = total as any;
        return;
      }
      Message.warning('获取数据失败');
    })
    .catch(() => {
      loading.value = false;
      Message.warning('获取数据失败');
    });
}

function handlerUploadError(err: any) {
  console.log(`[ err ]=>`, err);
  const { message } = err.response;
  Message.error(message);
}

// 添加资源
function assetAdd() {
  // 添加资源
  router.push({
    name: 'resourceadd'
  });
  console.log(`[ handleChick ]=>`);
}

// 查看资源
function viewAsset(item: T.TResourceItem) {
  console.log(item, 'item');
  const { id } = item;
  if (!id) return;
  router.push({
    name: 'resourcecheck',
    params: {
      id: id
    }
  });
}

const sourceDetails = (val)=>{
  router.push({
    name:"LookBloodtiesdetail",
    query:val
  });
}
// 操作事件
function handlerOperator(record: any, item: any) {
  console.log(`[ record ]=>`, record);
  console.log(`[ item ]=>`, item);
  if (!record || !item) return;
  if (item.code === 'view') {
    viewAsset(record);
  } else if (item.code === 'edit') {
    editAsset(record);
  } else if (item.code === 'delete') {
    deleteAsset(record);
  } else if (item.code === 'update') {
    updateAsset(record);
  } else if (item.code === 'version') {
    viewVersion(record);
  }else if (item.code === 'source') {
    sourceDetails(record);
  }
}
// 编辑资源
function editAsset(item: any) {
  if (!item || !item.id) return;
  router.push({
    name: 'resourceedit',
    params: {
      id: item.id
    }
  });
}
// 更新资源
function updateAsset(item: any) {
  if (!item || !item.id) return;
  router.push({
    name: 'resourceupdate',
    params: {
      id: item.id
    }
  });
}

// 删除资源
const removePopKey = ref(false);
const removePopData = ref<any>(null);
function deleteAsset(item: any) {
  removePopKey.value = true;
  removePopData.value = item;
}
function toRemove() {
  const { id } = removePopData.value;
  Api.RemoveResource(id)
    .then((rs) => {
      const { code, errMsg } = rs;
      if (code === 200) {
        Message.success('删除成功');
        getTableData();
      } else {
        Message.warning(`删除失败[${errMsg}]`);
      }
    })
    .catch((e) => {
      const { code, message } = e;
      if (code === 400) {
        Message.error(message);
      }
      console.log(`[ editAssete ]=>`, e);
    });
  removePopKey.value = false;
}

// // 查看关联
// function viewRelation(item: T.TResourceItem) {
//   if (!item || !item.id) return;
//   router.push({
//     name: 'Rebloodtiesdetail',
//     params: {
//       id: item.id
//     }
//   })
// }

// 查看版本
function viewVersion(item: T.TResourceItem) {
  if (!item || !item.id) return;
  router.push({
    name: 'checkVersion',
    params: {
      id: item.id
    }
  });
}

function watchEnterHandler(e: KeyboardEvent) {
  if (route.name != 'resource') return;
  if (e.key === 'Enter') {
    getTableData();
  }
}

onUnmounted(() => {
  // 移除键盘监听
  window.removeEventListener('keydown', watchEnterHandler);
});

onMounted(() => {
  getTableData();
  window.addEventListener('keydown', watchEnterHandler);
});


</script>

<style lang="less" scoped>
.circle-point {
  // @apple w-[12px] h-[12px] bg-[#00C853] rounded-full flex justify-center items-center;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border-width: 2px;
}
.more-fliter-box {
  .arco-row {
    .arco-col {
      @apply h-full flex justify-start items-center;
      padding: 0 10px;
      box-sizing: border-box;
    }
  }
}
.chunk-delete-box {
  .arco-modal-wrapper {
    .arco-modal {
      padding: 0px;
      .arco-modal-header,
      .arco-modal-footer {
        border: none;
      }
      .arco-modal-body {
        .chunk-delete-info-box {
          svg {
            color: #f1aa3c;
            width: 20px;
            height: 20px;
            position: relative;
            top: 2px;
          }
        }
      }
    }
  }
}
.search-item {
  border: 1px solid #d3dbeb;
  background-color: #fff;
  border-radius: 4px;
  height: 32px;
}

.common-col{
  display: flex;
  align-items: center;
}

.association-btn{
  background-color: #F0F4FA;
  color: #465A80;
  margin-right: 12px;
  border-radius: 4px
}

.main-container{
  height: 100%;
  overflow-y: scroll;
  padding-bottom: 24px;
}

::v-deep {
  .header-right-btn{
    .arco-btn-group{
      border-radius: 4px;
      overflow: hidden;
      
    }
    
  }
  
  .arco-select-view-prefix ,
  .arco-input-prefix,
  .arco-picker-prefix
  {
    color: #A3B0CC;
  }
  .search-item{
    .arco-input::placeholder {
      color: #d3dbeb;
      font-size: 14px;
    }

    .arco-picker-input input::placeholder{
      color: #D3DBEB;
    }
    .arco-select-view-input::placeholder{
      color: #D3DBEB;
    }

    
  } 
  .arco-select-view-single,
  .arco-picker
  {
    background-color: #fff;
  }

  .arco-table-th-title{
    color: #394D73;
  }

  .arco-table-td-content{
    color: #465A80;
  }
  .arco-modal-header{
    border-bottom: none;
  }
  .arco-modal-footer {
    border-top: none;
  }
}
</style>


